package com.bthdung.studios.lesson12.framework.program;

import android.opengl.GLES20;
import android.util.Log;

public class Program
{
	protected Effect effect;
	protected int id;
	
	public Effect glGetEffect()
	{
		return effect;
	}
	
	public Program(String vShaderCode, String fShaderCode)
	{
		effect = new Effect(vShaderCode, fShaderCode);
		id = glCreateProgram(effect.glGetVShader(), effect.glGetFShader());

		effect.glRetrieveAttributes(id);
		effect.glRetrieveUniforms(id);
		effect.glActivateAttributes();

		glUseProgram();
	}

	public void glUseProgram()
	{
		GLES20.glUseProgram(id);
	}

	public int getID()
	{
		return id;
	}

	// ////////////////////////////

	static protected int glCreateProgram(int vShader, int fShader)
	{
		int program = GLES20.glCreateProgram();

		if (program == 0) throw new RuntimeException("Error creating program.");

		GLES20.glAttachShader(program, vShader);
		GLES20.glAttachShader(program, fShader);
		GLES20.glLinkProgram(program);

		int[] params = new int[] { 0 };
		GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, params, 0);
		if (params[0] == 0)
		{
			String log = GLES20.glGetProgramInfoLog(program);
			GLES20.glDeleteProgram(program);
			Log.e("Program", log);

			throw new RuntimeException("Error creating program.");
		}

		return program;
	}
}
